<?php
// +----------------------------------------------------------------------+
// | Author:  Evgeny Leontev <eleontev@gmail.com>                         |
// | Copyright (c) 2005 Evgeny Leontev                                    |
// +----------------------------------------------------------------------+
// | This source file is free software; you can redistribute it and/or    |
// | modify it under the terms of the GNU Lesser General Public           |
// | License as published by the Free Software Foundation; either         |
// | version 2.1 of the License, or (at your option) any later version.   |
// |                                                                      |
// | This source file is distributed in the hope that it will be useful,  |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of       |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU    |
// | Lesser General Public License for more details.                      |
// +----------------------------------------------------------------------+

// ASSORTED CLASSES AND FUNCTIONS INCLUDED ON EVERY REQUEST
class Registry
{
	var $_cache;
	
	function Registry() {
		$this->_cache = array();
	}
	
	function setEntry($key, &$item) {
		$this->_cache[$key] = &$item;
	}
	
	function & getEntry($key) {
		return $this->_cache[$key];
	}
	
	function isEntry($key) {
		return ($this->getEntry($key) !== null);
	}
	
	function & instance() {
		static $registry;
		if (!$registry) { $registry = new Registry(); }
		return $registry;
	}
}



// to place all useful functions if not sure where to place
class ExtFunc
{
	
	// @example valueToArray($elem1, $elem2, $elem3, ...);
	// @return array('$elem1' => '$elem1', ...);
	function valueToArray($elem) {
		$ar = func_get_args();
		foreach($ar as $v) {
			$new_ar[$v] = $v;
		}
		return $new_ar;
	}
	
	
	// recursive
	function arrayToString(&$arr, $glue = ',') { 
		foreach($arr as $k => $v) {
			if(is_array($v)) { 
				$arr[$k] = ExtFunc::arrayToString($v, $glue);
			}
		}
		return (join($glue, $arr));
	}
}



class WebUtil
{

	function getIP() {
		$ip = 'UNKNOWN';
		if    (getenv('HTTP_CLIENT_IP'))       { $ip = getenv('HTTP_CLIENT_IP'); }
		elseif(getenv('HTTP_X_FORWARDED_FOR')) { $ip = getenv('HTTP_X_FORWARDED_FOR'); }
		elseif(getenv("REMOTE_ADDR"))          { $ip = getenv("REMOTE_ADDR"); }
		return $ip;
	}
	
	
	function serialize_url($url) {
		return rawurlencode(serialize($url));
	}
	
	
	function unserialize_url($url) {
		return unserialize(urldecode(stripslashes($url)));
	}
	
	
	function getFileSize($file){
		
		if(is_numeric($file))
			$file_size = $file+0;
		else
			$file_size = filesize($file);
		
		
		if ($file_size >= 1073741824)
			$file_size = round($file_size / 1073741824 * 100) / 100 ." gb"; 
			
		elseif ($file_size >= 1048576)
			$file_size = round($file_size / 1048576 * 100) / 100 ." mb"; 
			
		elseif ($file_size >= 1024)
			$file_size = round($file_size / 1024 * 100,-2) / 100 ." kb"; 
			
		else 
			$file_size = round($file_size) . " b"; 
		
		return $file_size;
	}

}



class DBUtil
{

	function error($sql = null, $real_error = false) {
		
		require_once 'eleontev/HTML/BoxMsg.php';
		
		$reg = &Registry::instance();
		$conf = &$reg->getEntry('conf');
		$msgs =& AppMsg::getMsgs('error_msg.ini', false, 'db_error', 1);
		
		if($conf['debug_info'] || $real_error) {
		
			$html =  '<div style="font-size: 12px;">';
			$html .= '<b>SQL ERROR:</b> ' . mysql_error() . '<br>';
			$html .= '<b>CODE:</b> ' . mysql_errno() . '<br>';
			$html .= '<b>SQL: </b><pre>' . print_r($sql, 1) . '</pre>';
			$html .= '</div>';
		
			$msgs['body'] = $html;
		}
		
		return BoxMsg::factory('error', $msgs);
	}
	
	
	function &connect($conf) {
	
		//global $CACHED, $EXECS;
		
		//$dsn = 'mysql://root:pwd@localhost/mydb'; 
		//$str = '%s://%s:%s@%s/%s?port=%s';
		//$dsn = sprintf($str, $conf['db_driver'], $conf['db_user'], $conf['db_pass'], $conf['db_host'], $conf['db_base'], $conf['db_port']);
		//echo "<pre>"; print_r($dsn); echo "</pre>";
		//$db = ADONewConnection($dsn)  or die (DBUtil::error('', true));
		
		$db = ADONewConnection($conf['db_driver']);
		@$db->Connect($conf['db_host'], $conf['db_user'], $conf['db_pass'], $conf['db_base']) or die (DBUtil::error('Connect Error', true));
		$db->SetFetchMode(ADODB_FETCH_ASSOC);
		$db->ADODB_COUNTRECS = false;
		$db->debug = $conf['debug_db'];
		
		//echo "<pre>"; print_r($db); echo "</pre>";
		//$db->fnExecute = 'CountExecs';
		//$db->fnCacheExecute = 'CountCachedExecs';
		
		return $db;
	}
	
	
	function beginTrans() {
		mysql_query('SET AUTOCOMMIT=0') or die (DBUtil::error('SET AUTOCOMMIT=0'));
		mysql_query('START TRANSACTION') or die (DBUtil::error('START TRANSACTION'));
	}


	function commitTrans() {
		mysql_query('COMMIT') or die (DBUtil::error('COMMIT'));
		mysql_query('SET AUTOCOMMIT=1') or die (DBUtil::error('SET AUTOCOMMIT=1'));
	}
}


/*
// from manual
function CountExecs($db, $sql, $inputarray) {
   global $EXECS;
   $EXECS++;
}

function CountCachedExecs($db, $secs2cache, $sql, $inputarray) {
   global $CACHED;
   $CACHED++;
}

// display stat
//echo '<br><br>';
//echo 'All db queries: <b>'.($EXECS+$CACHED).'</b><br>';
//echo 'Cached queries : <b>'.$CACHED.'</b>'; 
*/


// SOME FUNCTIONS
function db_error($sql = null) {
	return DBUtil::error($sql);
}

function &db_connect($conf) {
	return DBUtil::connect($conf);
}



// to make siglton from any class
// $reg =& Singleton('ClassName');
function & Singleton($class) {
	static $instances;
	
	if (!is_array($instances)) {
	     $instances = array();
	}
	
	if (!isset($instances[$class])) {
		$instances[$class] =& new $class;
	}
	
	return $instances[$class];
}


// return false if version of php is less than $ver
function checkPHP($ver = '5.0.2') {
	$current_ver = (int) str_replace('.', '', PHP_VERSION);
	$needed_ver  = (int) str_replace('.', '', $ver);
	
	return ($current_ver > $needed_ver);
}


function getDebugInfo() {
	require_once 'eleontev/HTML/BoxMsg.php';
	
	$arr = array('GET'=>$_GET, 'SESSION'=>$_SESSION,  'POST'=>$_POST,'COOKIE'=>$_COOKIE, 'FILES'=>$_FILES);
	$str = '<span style="font-size: 11px;"><pre>%s</pre></span>';
	
	$html[] = '<table align="center" width="70%"><tr><td><br>';
	
	foreach($arr as $k => $v) {
		//if(!$v) { continue; }
		$msgs = array();
		$msgs['title'] = $k;
		$msgs['body']  = ($v) ? sprintf($str, print_r($v, 1)) : false;
		$html[] = BoxMsg::quickGet($msgs);			
	}

	$html[] = '</td></tr></table>';
	
	//echo "<pre>"; print_r(apache_request_headers()); echo "</pre>";
	
	return implode('', $html);
}


// build hidden fields from array of params
function http_build_hidden($formdata, $numeric_prefix = null) {

      // If $formdata is an object, convert it to an array
      if (is_object($formdata)) {
          $formdata = get_object_vars($formdata);
      }

      // Check we have an array to work with
      if (!is_array($formdata)) {
          trigger_error('http_build_hidden() Parameter 1 expected to be Array or Object. Incorrect value given.', E_USER_WARNING);
          return false;
      }

      // If the array is empty, return null
      if (empty($formdata)) {
          return;
      }

      // Start building the query
      $tmp = array ();
      foreach ($formdata as $key => $val)
      {
          if (is_integer($key) && $numeric_prefix != null) {
              $key = $numeric_prefix . $key;
          }

          if (is_scalar($val)) {
			 // array_push($tmp, sprintf('<input type="hidden" name="%s" value="%s">', urlencode($key), urlencode($val)));
			  array_push($tmp, sprintf('<input type="hidden" name="%s" value="%s" />', urldecode($key), urldecode($val)));      
	          continue;
          }

          // If the value is an array, recursively parse it
          if (is_array($val)) {
              //array_push($tmp, __http_build_hidden($val, urlencode($key)));
			  array_push($tmp, __http_build_hidden($val, urldecode($key)));
              continue;
          }
      }

      return implode("\n", $tmp);
  }

  // Helper function
  function __http_build_hidden ($array, $name)
  {
      $tmp = array ();
      foreach ($array as $key => $value)
      {
          if (is_array($value)) {
			  array_push($tmp, __http_build_hidden($value, sprintf('%s[%s]', $name, $key)));
          }

          elseif (is_scalar($value)) {
			//  array_push($tmp, sprintf('<input type="hidden" name="%s[%s]" value="%s" />', $name, urlencode($key), urlencode($value)));
          		array_push($tmp, sprintf('<input type="hidden" name="%s[%s]" value="%s" />', $name, urldecode($key), urldecode($value)));
		  }

          elseif (is_object($value)) {
              array_push($tmp, __http_build_hidden(get_object_vars($value), sprintf('%s[%s]', $name, $key)));
          }
      }

      return implode("\n", $tmp);
  }
  
  
if(!function_exists('array_diff_key')) {
	
	function array_diff_key($arr_reduced, $arr_needed) {
		$r = array();
		foreach($arr_needed as $v) {
			$r[$v] = $arr_reduced[$v];
		}
		
		return $r;
	}
}
?>